/*
 * Copyright (C) 2015 yixun All Rights Reserved.
 * 
 * PremisesController.java
 */
package com.yixun.qfbao.xf.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yixun.common.controller.BaseController;
import com.yixun.common.exception.YIXUNExceptionCode;
import com.yixun.common.exception.YIXUNUNCheckedException;
import com.yixun.common.page.Page;
import com.yixun.common.page.PageUtil;
import com.yixun.qfbao.api.service.MarketingAccountApiService;
import com.yixun.qfbao.model.Area;
import com.yixun.qfbao.model.BaseCodeValue;
import com.yixun.qfbao.model.dto.AreaDto;
import com.yixun.qfbao.model.dto.DistributionAuditDto;
import com.yixun.qfbao.model.enums.DecorationTypeEnum;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.service.AreaService;
import com.yixun.qfbao.service.BaseCodeValueService;
import com.yixun.qfbao.service.DistributionAuditService;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.xf.controller.vo.PremisesVo;
import com.yixun.qfbao.xf.model.ApartmentLayoutDiagram;
import com.yixun.qfbao.xf.model.BusinessCircles;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.ApartmentLayoutDiagramDto;
import com.yixun.qfbao.xf.model.dto.PremisesDto;
import com.yixun.qfbao.xf.model.enums.BuildingTypeEnum;
import com.yixun.qfbao.xf.model.enums.EstateTypeEnum;
import com.yixun.qfbao.xf.model.enums.PositionTypeEnum;
import com.yixun.qfbao.xf.model.enums.SaleStatusEnum;
import com.yixun.qfbao.xf.service.ApartmentLayoutDiagramService;
import com.yixun.qfbao.xf.service.BusinessCirclesService;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * [文件名称]<br>
 * PremisesController.java<br>
 * <br>
 * [文件描述]<br>
 * 楼盘信息 Controller<br>
 * <br>
 * [修改记录]<br>
 * 2015-10-14 15:34:13 创建 陶俊代码生成器<br>
 * 
 * @author 陶俊代码生成器
 * @version 1.00
 */
@Controller
@RequestMapping("/xf/premises")
public class PremisesController extends BaseController {
	@Autowired
	private PremisesService mservice;
	@Autowired
	private BusinessCirclesService businessCirclesService;
	@Autowired
	private AreaService areaService;
	@Autowired
	private ApartmentLayoutDiagramService apartmentLayoutDiagramService;
	@Autowired
	private BaseCodeValueService baseCodeValueService;
	@Autowired
	private DistributionAuditService distributionAuditService;
	@Autowired
	private MarketingAccountApiService marketingAccountApiService;
	private static Logger log = Logger.getLogger(PremisesController.class);
	
	@RequestMapping({"/manage"})
	public String index(Model model){
		return "/xf/premises/manage";
	}
	
	@RequestMapping("/list")
	public @ResponseBody Page<Premises> indexJson(PremisesVo entity,HttpServletResponse response,int page,int rows){
		Page<Premises> pageModel = null;
		try {
			if(null != entity.getShelvesStatus() && entity.getShelvesStatus() == -1){
				entity.setShelvesStatus(null);
			}
			entity.setOrders("t.create_time desc");
			entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			pageModel = mservice.getPageModel(entity.toDto(),PageUtil.begin(page,rows),PageUtil.end(page,rows));
			List<Premises> row = pageModel.getRows();
			for(Premises pre:row){
				if(org.apache.commons.lang.StringUtils.isNotBlank(pre.getCodeName())){
					String[] codeNames = pre.getCodeName().split(",");
					StringBuffer sb = new StringBuffer();
					for(String id:codeNames){
						BaseCodeValue bcv = baseCodeValueService.selectById(Long.parseLong(id));
						if(bcv!=null){
							sb.append(bcv.getCodeName()+",");
						}
					}
					if(sb.toString().length()>0){
						pre.setCodeName(sb.toString().substring(0, sb.toString().length()-1));
					}else{
						pre.setCodeName("");
					}
					sb.setLength(0);
				}
			}
		}catch (YIXUNUNCheckedException e) {
			log.error("分页信息失败: {}",e);
			pageModel = new Page<Premises>();
			pageModel.setErrorMsg(e.getCode()+":"+e.getOutMsg());
		}catch (Exception e) {
			log.error("分页信息失败: {}",e);
			pageModel = new Page<Premises>();
			pageModel.setErrorMsg(YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout());
		}
		return pageModel;
	}
	
	@RequestMapping("/view")
	public String formView(Model model,PremisesVo entity,HttpServletResponse response,Boolean isBack) throws IOException{
		try {
			if(isBack!=null&&isBack.booleanValue()){
				//model.addAttribute("model",entity);
			}else{
				BeanUtils.copyProperties(mservice.selectBy(entity), entity);
				if(entity.getId() !=null){
					ApartmentLayoutDiagramDto apartmentLayoutDiagramDto = new  ApartmentLayoutDiagramDto();
					apartmentLayoutDiagramDto.setPremisesId(entity.getId());
				}
			}
			model.addAttribute("model",entity);
		}catch (YIXUNUNCheckedException e) {
			log.error("创建失败: {}",e);
		}catch (Exception e) {
			log.error("创建失败: {}",e);
		}
		return "/xf/premises/save_edit";
	}
	
	@RequestMapping("/check")
	public String check(Model model,PremisesVo entity,HttpServletResponse response,Boolean isBack) throws IOException{
		try {
			if(isBack!=null&&isBack.booleanValue()){
				//model.addAttribute("model",entity);
			}else{
				Premises en = mservice.selectBy(entity);
				if(org.apache.commons.lang.StringUtils.isNotBlank(en.getCodeName())){
					String[] codeNames = en.getCodeName().split(",");
					StringBuffer sb = new StringBuffer();
					for(String id:codeNames){
						BaseCodeValue bcv = baseCodeValueService.selectById(Long.parseLong(id));
						sb.append(bcv.getCodeName()+",");
					}
					en.setCodeName(sb.toString().substring(0, sb.toString().length()-1));
					sb.setLength(0);
				}
				BeanUtils.copyProperties(en, entity);
				if(entity.getId() !=null){
					ApartmentLayoutDiagramDto apartmentLayoutDiagramDto = new  ApartmentLayoutDiagramDto();
					apartmentLayoutDiagramDto.setPremisesId(entity.getId());
					entity.setApartmentsList(JSONObject.toJSONString(apartmentLayoutDiagramService.selectListByDto(apartmentLayoutDiagramDto)));
					entity.setApartmentsList(JSONObject.toJSONString(apartmentLayoutDiagramService.selectListByDto(apartmentLayoutDiagramDto)));
					if(StringUtils.isNotBlank(entity.getEstateType())) {
						String[] estateTypeArray = entity.getEstateType().split("[,]");
						String estateTypeStr = "";
						for(String estateType: estateTypeArray) {
							estateTypeStr += EstateTypeEnum.getByNo(estateType).getDes() + ",";
						}
						entity.setEstateType(estateTypeStr);
					}
					StringBuilder sb = new StringBuilder();
					if (null != entity.getBuildingType()) {
						if(entity.getBuildingType().indexOf(",")!=-1){
							String[] buildingTypes = entity.getBuildingType().split(",");
							for(String no:buildingTypes){
								sb.append(BuildingTypeEnum.getByNo(no).getDes()+",");
							}
							entity.setBuildingType(sb.substring(0, sb.length()-1));
						}else{
							entity.setBuildingType(BuildingTypeEnum.getByNo(entity.getBuildingType()).getDes());
						}
					}
					entity.setDecorationType(DecorationTypeEnum.getByNo(entity.getDecorationType()).getDes());
					if(StringUtils.isNotBlank(entity.getPositionType()))
					entity.setPositionType(PositionTypeEnum.getByNo(entity.getPositionType()).getDes());
					entity.setSaleStatus(SaleStatusEnum.getByNo(entity.getSaleStatus()).getDes());
					AreaDto areaDto = new AreaDto();
					areaDto.setId(entity.getAreaId());
					Area area = areaService.selectBy(areaDto);
					entity.setArea(area);
				}
				
				ApartmentLayoutDiagramDto entit=new ApartmentLayoutDiagramDto();
				entit.setPremisesId(entity.getId());
				List<ApartmentLayoutDiagram> diagramList = apartmentLayoutDiagramService.selectListByDto(entit);
				if(null != diagramList){
					model.addAttribute("diagramList", diagramList);
				}
			}
			if(StringUtils.isNotEmpty(entity.getCommissionWay())){
				if("1".equals(entity.getCommissionWay())){
					entity.setCommissionWay("签约结佣");
				}else if("2".equals(entity.getCommissionWay())){
					entity.setCommissionWay("按揭结佣");
				}
			}
			
			String commission = "";
			if(StringUtils.isNotBlank(entity.getCommission())) {
				JSONArray jsonArray = JSONArray.parseArray(entity.getCommission());
				if(null != jsonArray && jsonArray.size() > 0) {
					for(int ii=0; ii<jsonArray.size(); ii++) {
						JSONObject jsonObject = jsonArray.getJSONObject(ii);
						commission += jsonObject.getString("name")+": " + jsonObject.getString("typeValue") + " " + jsonObject.getString("type");
						if(ii != jsonArray.size() - 1) {
							commission += "、";
						}
					}
				}
			}
			entity.setCommission(commission);
			
			model.addAttribute("model",entity);
		}catch (YIXUNUNCheckedException e) {
			log.error("创建失败: {}",e);
		}catch (Exception e) {
			log.error("创建失败: {}",e);
		}
		return "/xf/premises/check";
	}
	
	@RequestMapping("/audit")
	public String audit(Model model,PremisesVo entity,HttpServletResponse response,String statusValue) throws IOException{
		String errorMsg = null;
		try {
			PremisesDto premisesDto = new PremisesDto();
			premisesDto.setId(entity.getId());
			premisesDto.setPremisesStatus(entity.getPremisesStatus());
			premisesDto.setRemark(entity.getRemark());
			mservice.audit(premisesDto);
		}catch (YIXUNUNCheckedException e) {
			log.error("编辑失败: {}",e);
			errorMsg = e.getCode()+":"+e.getOutMsg();
		}catch (Exception e) {
			errorMsg = YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout();
			log.error("编辑失败: {}",e);
		}
		if(StringUtils.isNotBlank(errorMsg)){
			model.addAttribute("errorMsg", errorMsg);
			return formView(model,entity,response,true);
		}
		return "forward:manage";
	}
	
	@RequestMapping("/save_edit")
	public String saveOrUpdate(Model model,PremisesVo entity,HttpServletResponse response) throws IOException{
		String errorMsg = null;
		try {
			Long bcid = entity.getBusinessCirclesId();
			if(bcid!=null&&bcid.longValue()>0){
				BusinessCircles businessCircles  = businessCirclesService.selectById(bcid);
				entity.setAreaId(businessCircles.getAreaId());
			}
			if(entity!=null&&entity.getId()!=null){
				mservice.update(entity);
				//没有id 则为新增可售户型
				if(entity.getApartmentsList() !=null){
					List<ApartmentLayoutDiagramDto> apartmentLayoutDiagramDtoList = JSONObject.parseArray(entity.getApartmentsList(),ApartmentLayoutDiagramDto.class);
					for(ApartmentLayoutDiagramDto apartmentLayoutDiagramDto: apartmentLayoutDiagramDtoList){
						if(apartmentLayoutDiagramDto !=null && apartmentLayoutDiagramDto.getId()==null){
							apartmentLayoutDiagramDto.setPremisesId(entity.getId());
							apartmentLayoutDiagramService.create(apartmentLayoutDiagramDto);
						}
					}
				}
			}else{
				mservice.create(entity);
				//没有id 则为新增可售户型
				if(entity.getApartmentsList() !=null){
					List<ApartmentLayoutDiagramDto> apartmentLayoutDiagramDtoList = JSONObject.parseArray(entity.getApartmentsList(),ApartmentLayoutDiagramDto.class);
					for(ApartmentLayoutDiagramDto apartmentLayoutDiagramDto: apartmentLayoutDiagramDtoList){
						if(apartmentLayoutDiagramDto !=null && apartmentLayoutDiagramDto.getId()==null){
							apartmentLayoutDiagramDto.setPremisesId(entity.getId());
							apartmentLayoutDiagramService.create(apartmentLayoutDiagramDto);
						}
					}
				}
			}
		}catch (YIXUNUNCheckedException e) {
			log.error("编辑失败: {}",e);
			errorMsg = e.getCode()+":"+e.getOutMsg();
		}catch (Exception e) {
			errorMsg = YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout();
			log.error("编辑失败: {}",e);
		}
		if(StringUtils.isNotBlank(errorMsg)){
			model.addAttribute("errorMsg", errorMsg);
			return formView(model,entity,response,true);
		}
		return "forward:manage";
	}
	@RequestMapping("/del")
	public @ResponseBody Map<String,Object> destroy(PremisesVo entity,HttpServletResponse response) throws IOException{
		Map<String,Object> res = new HashMap<String, Object>();
		try {
			int destroyCount = mservice.destroy(entity.toDto());
			res.put("count",destroyCount);
			res.put("row",entity.toDto());
		}catch (YIXUNUNCheckedException e) {
			log.error("删除失败: {}",e);
			res.put("errorMsg",e.getCode()+":"+e.getOutMsg());
		}catch (Exception e) {
			log.error("删除失败: {}",e);
			res.put("errorMsg",YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout());
		}
		return res;
	}
	
	@RequestMapping("/combo")
	public @ResponseBody List<Premises> combo(PremisesVo entity,HttpServletResponse response){
		List<Premises> bcs = new ArrayList<Premises>();
		try {
			if("all".equals(entity.getSaleStatus())) {
				entity.setSaleStatus(null);
			}else {
				entity.setSaleStatus(SaleStatusEnum.type_1.getNo());
			}
			
			bcs = mservice.getPageModel(entity.toDto(),0,1000).getRows();
		}catch (YIXUNUNCheckedException e) {
			log.error("分页信息失败: {}",e);
		}catch (Exception e) {
			log.error("分页信息失败: {}",e);
		}
		return bcs;
	}
	@RequestMapping("/changeShelvesStatus")
	public @ResponseBody Map<String,Object> changeShelvesStatus(PremisesVo entity, HttpServletResponse response){
		Map<String,Object> res = new HashMap<String, Object>();
		if(entity.getId() == null){
			res.put("result","0");
			res.put("msg","id不能为空");
			return res;
		}
		if(entity.getShelvesStatus() == null){
			res.put("result","0");
			res.put("msg","状态为空");
			return res;
		}
		try{
			PremisesDto premisesDto = new PremisesDto();
			if("1".equals(entity.getShelvesStatus().toString())){
				premisesDto.setShelvesStatus(0l);
			}else{
				premisesDto.setShelvesStatus(1l);
			}
			premisesDto.setId(entity.getId());
			mservice.audit(premisesDto);

			res.put("result","1");
			res.put("msg","上下架成功");

		}catch (YIXUNUNCheckedException e){
			log.error("上下架失败: {}",e);
			res.put("result","0");
		}catch (Exception e){
			log.error("上下架失败: {}",e);
			res.put("result","0");
		}
		return res;
	}

	@RequestMapping({"/distributionPremises"})
	public String distributionPremises(Model model){
		return "/xf/premises/audit_premises";
	}
	@RequestMapping("/getDistributionPremises")
	public @ResponseBody Page<DistributionAuditDto> getDistributionPremises(DistributionAuditDto entity, HttpServletResponse response,int page,int rows){
		entity.setOrders(" t.audit_status desc,t.apply_time desc");
		Page<DistributionAuditDto> pageModel = distributionAuditService.getPageList(entity,PageUtil.begin(page,rows),PageUtil.end(page,rows));
		return pageModel;
	}


	@RequestMapping("/auditDistributionPremises")
	public @ResponseBody Map<String,Object> auditDistributionPremises(DistributionAuditDto entity, HttpServletResponse response){
		Map<String,Object> res = new HashMap<String, Object>();
		if(entity.getId() == null){
			res.put("result","0");
			res.put("msg","id不能为空");
			return res;
		}
		if(entity.getAuditStatus() == null){
			res.put("result","0");
			res.put("msg","未选择审核状态");
			return res;
		}
		try {
			entity.setCheckTime(Calendar.getInstance().getTime());
			int i = distributionAuditService.update(entity);
			if(i > 0){
				res.put("result","1");
				res.put("msg","操作成功");
			}else{
				res.put("result","0");
			}
		}catch (YIXUNUNCheckedException e){
			log.error("审核失败: {}",e);
			res.put("result","0");
		}catch (Exception e){
			log.error("审核失败: {}",e);
			res.put("result","0");
		}

		return res;
	}
	
	@RequestMapping({"/outsidePremisesManage"})
	public String outsidePremisesManage(Model model){
		return "/outside/premises/manage";
	}
	
	@RequestMapping("/outsidePremisesList")
	public @ResponseBody Page<PremisesDto> outsidePremisesList(PremisesVo entity,HttpServletResponse response,int page,int rows){
		Page<PremisesDto> pageModel = null;
		try {
			if(null != entity.getShelvesStatus() && entity.getShelvesStatus() == -1){
				entity.setShelvesStatus(null);
			}
			entity.setOrders("c.company_name, t.create_time desc");
			pageModel = mservice.getOutsidePremisesPage(entity.toDto(), PageUtil.begin(page,rows), rows);
		}catch (YIXUNUNCheckedException e) {
			log.error("分页信息失败: {}",e);
			pageModel = new Page<PremisesDto>();
			pageModel.setErrorMsg(e.getCode()+":"+e.getOutMsg());
		}catch (Exception e) {
			log.error("分页信息失败: {}",e);
			pageModel = new Page<PremisesDto>();
			pageModel.setErrorMsg(YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout());
		}
		return pageModel;
	}
	
	@RequestMapping("/outsidePremisesCheck")
	public String outsidePremisesCheck(Model model,PremisesVo entity,HttpServletResponse response,Boolean isBack) throws IOException{
		try {
			if(isBack!=null&&isBack.booleanValue()){
				//model.addAttribute("model",entity);
			}else{
				Premises en = mservice.selectBy(entity);
				if(org.apache.commons.lang.StringUtils.isNotBlank(en.getCodeName())){
					String[] codeNames = en.getCodeName().split(",");
					StringBuffer sb = new StringBuffer();
					for(String id:codeNames){
						BaseCodeValue bcv = baseCodeValueService.selectById(Long.parseLong(id));
						sb.append(bcv.getCodeName()+",");
					}
					en.setCodeName(sb.toString().substring(0, sb.toString().length()-1));
					sb.setLength(0);
				}
				BeanUtils.copyProperties(en, entity);
				if(entity.getId() !=null){
					ApartmentLayoutDiagramDto apartmentLayoutDiagramDto = new  ApartmentLayoutDiagramDto();
					apartmentLayoutDiagramDto.setPremisesId(entity.getId());
					entity.setApartmentsList(JSONObject.toJSONString(apartmentLayoutDiagramService.selectListByDto(apartmentLayoutDiagramDto)));
					entity.setApartmentsList(JSONObject.toJSONString(apartmentLayoutDiagramService.selectListByDto(apartmentLayoutDiagramDto)));
					if(StringUtils.isNotBlank(entity.getEstateType())) {
						String[] estateTypeArray = entity.getEstateType().split("[,]");
						String estateTypeStr = "";
						for(String estateType: estateTypeArray) {
							estateTypeStr += EstateTypeEnum.getByNo(estateType).getDes() + ",";
						}
						entity.setEstateType(estateTypeStr);
					}
					StringBuilder sb = new StringBuilder();
					if (null != entity.getBuildingType()) {
						if(entity.getBuildingType().indexOf(",")!=-1){
							String[] buildingTypes = entity.getBuildingType().split(",");
							for(String no:buildingTypes){
								sb.append(BuildingTypeEnum.getByNo(no).getDes()+",");
							}
							entity.setBuildingType(sb.substring(0, sb.length()-1));
						}else{
							entity.setBuildingType(BuildingTypeEnum.getByNo(entity.getBuildingType()).getDes());
						}
					}
					if(StringUtils.isNotBlank(entity.getDecorationType())) {
						entity.setDecorationType(DecorationTypeEnum.getByNo(entity.getDecorationType()).getDes());
					}
					if(StringUtils.isNotBlank(entity.getPositionType())) {
						entity.setPositionType(PositionTypeEnum.getByNo(entity.getPositionType()).getDes());
					}
					if(StringUtils.isNotBlank(entity.getSaleStatus())) {
						entity.setSaleStatus(SaleStatusEnum.getByNo(entity.getSaleStatus()).getDes());
					}
					AreaDto areaDto = new AreaDto();
					areaDto.setId(entity.getAreaId());
					Area area = areaService.selectBy(areaDto);
					entity.setArea(area);
				}
				
				ApartmentLayoutDiagramDto entit=new ApartmentLayoutDiagramDto();
				entit.setPremisesId(entity.getId());
				List<ApartmentLayoutDiagram> diagramList = apartmentLayoutDiagramService.selectListByDto(entit);
				if(null != diagramList){
					model.addAttribute("diagramList", diagramList);
				}
			}
			if(StringUtils.isNotEmpty(entity.getCommissionWay())){
				if("1".equals(entity.getCommissionWay())){
					entity.setCommissionWay("签约结佣");
				}else if("2".equals(entity.getCommissionWay())){
					entity.setCommissionWay("按揭结佣");
				}
			}
			String commission = "";
			if(StringUtils.isNotBlank(entity.getCommission())) {
				JSONArray jsonArray = JSONArray.parseArray(entity.getCommission());
				if(null != jsonArray && jsonArray.size() > 0) {
					for(int ii=0; ii<jsonArray.size(); ii++) {
						JSONObject jsonObject = jsonArray.getJSONObject(ii);
						commission += jsonObject.getString("name")+": " + jsonObject.getString("typeValue") + " " + jsonObject.getString("type");
						if(ii != jsonArray.size() - 1) {
							commission += "、";
						}
					}
				}
			}
			entity.setCommission(commission);
			model.addAttribute("model",entity);
		}catch (YIXUNUNCheckedException e) {
			log.error("创建失败: {}",e);
		}catch (Exception e) {
			log.error("创建失败: {}",e);
		}
		return "/outside/premises/check";
	}

	/**
	 * 绑定营销号
	 * @param entity
	 * @param response
	 * @return
	 */
	@RequestMapping("/bindMarketingAccount")
	public @ResponseBody Map<String,Object> bindMarketingAccount(PremisesVo entity,HttpServletResponse response){
		Map<String,Object> res = new HashMap<String, Object>();
		res.put("result","0");
		String account = "";
		try{
			//参数校验
			if(entity.getId() == null){
				res.put("errorMsg","楼盘id为空");
				return res;
			}
			if(entity.getBindStatus() == null){
				res.put("errorMsg","绑定状态为空");
				return res;
			}
			//解绑
			if("0".equals(entity.getBindStatus())){
				account = marketingAccountApiService.unBindMarketingAccount(entity.getId());
			}else if("1".equals(entity.getBindStatus())){
				account = marketingAccountApiService.bindMarketingAccount(entity.getId(),entity.getMobile());
			}else{
				res.put("errorMsg","绑定状态参数错误");
				return res;
			}
		} catch (TServerException e){
			log.error("绑定营销号失败A: {}", e);
			res.put("errorMsg",e.getMessage());
			return res;
		} catch (Exception e){
			log.error("绑定营销号失败B: {}",e);
			res.put("errorMsg","绑定营销号失败");
			return res;
		}
		res.put("result","1");
		res.put("data",account);
		return res;
	}
}
